import fs from "fs-extra";
import { BaseTask, TaskResult } from "../../common/tasks/BastTask.js";
import { WebGLEnv } from "../WebGLEnv.js";
import path from "path";
import { toolchain } from "../../toolchain.js";
import _ from "lodash";
import { emphasize } from "../../tools/alert.js";
import { getHudsonLogURL } from "../../tools/vendor.js";

export interface WebGLCompressResult {
    compressed: boolean
    guidence?: string
}

export class WebGLCompressTextureTask extends BaseTask<WebGLCompressResult> {
    async run(): Promise<TaskResult<WebGLCompressResult>> {
        // 压缩贴图
        const compressed = toolchain.unity.supportCompressTex();
        let data: WebGLCompressResult = { compressed };
        if (compressed) {
            data = await this.compressTexture();
            
            console.log('compress texture finished, start copy min assets');
    
            // 拷贝压缩后的资源到cdn
            const exportRoot = path.join(toolchain.params.workSpacePath, WebGLEnv.ExportMiniGameRoot);
            const cdn = path.join(toolchain.params.uploadPath, WebGLEnv.MiniGameAssetRoot);
            await fs.copy(path.join(exportRoot, WebGLEnv.WebglCompressedOut), cdn);
        } else {
            console.log('compress texture is disabled');
        }
        return { success: true, errorCode: 0, data };
    }

    private async compressTexture(): Promise<WebGLCompressResult> {
        let uploadPath = toolchain.params.uploadPath;
        if(uploadPath[uploadPath.length - 1] != path.sep) uploadPath += path.sep;
        const params = ['-batchmode', '-projectPath', toolchain.params.workSpacePath, '-executeMethod', 'BuildCommand.CreateWXAssetBundles', 
        '-UploadResDir', uploadPath, '-platform', this.cmdOption.platform,
        '-defines', 'PUBLISH', '-quit'];
        const cmd = await toolchain.unity.runUnityCommand(this.cmdOption, params, 'CompressTexture');

        const result: WebGLCompressResult = { compressed: true };
        let guidence = '';
        // 检查Output failed的情况
        if (cmd.output.includes('wx compress texture failed')) {
            guidence = '部分贴图压缩失败';
        }
        const mch = cmd.output.match(/(?<=Error: The TextureFormat of picture \[).+?(?=\] is .+ , cannot get its texture, please use DXT5 then try again!)/g);
        if (mch != null) {
            const errorTexs: string[] = [];
            for (const tex of mch) {
                if (tex.startsWith('Lightmap-')) continue;
                errorTexs.push(tex);
            }

            if (errorTexs.length > 0) {
                toolchain.buildMessages.push('部分贴图格式错误，将导致部分机型显示异常');
    
                if (guidence) guidence += '\n';
                guidence += `以下${errorTexs.length}张贴图格式错误，部分机型不支持，请${emphasize('Override For WebGL')}并设置格式为${emphasize('RGBA Compressed DXT5|BC3')}:\n`
                guidence += errorTexs.join(', ');
                guidence += `\n点击查看日志：[构建日志](${getHudsonLogURL()})`
                result.guidence = guidence;
            }
        }
        return result;
    }

    get skip(): boolean {
        return !this.cmdOption.webglCompressTex;
    }
}
